//
//  LoginView.swift
//  GreenDeal
//
//  Created by Moennig Q on 1/2/2023.
//

import UIKit
import SnapKit
import IQKeyboardManagerSwift
class LoginView: View {
    let backView = IQPreviousNextView()
    let loginImageViewSize: CGSize = CGSize(width: 332, height: 192)
    let emailTextField = DIYTextField()
    let pwdTextField = DIYTextField()
    let loginBtn = OperationButton(R.string.localizable.login())
    let forgotPwdBtn = BaseButton()
    let registerBtn = BaseButton()
    lazy var moreLoginOptions: UIButton = {
        let btn = BaseButton()
        btn.setTitleColor(UIColor(hexStr: "#379657"), for: UIControl.State.normal)
        btn.setTitle("More Options", for: UIControl.State.normal)
        btn.setFont(R.font.interMedium(size: 14))
        return btn
    }()
    
    lazy var loginOptionsMenuView: LoginOptionsMenuView = {
        return LoginOptionsMenuView()
    }()
    override func setUpView() {
        self.backgroundColor = .white
        var backViewMargin: CGFloat = 30
        var topBottomMargin: CGFloat = 10
        if UIDevice.getCurrentDeviceType() == APPConfig.iPadType {
            backViewMargin = 150
            topBottomMargin = 100
        }
        
        let scrollView = DIYScrollView()
        self.addSubview(scrollView)
        scrollView.snp.makeConstraints { make in
            make.top.equalTo(self.safeAreaLayoutGuide.snp.top).offset(topBottomMargin)
            make.left.right.equalTo(self)
            make.bottom.equalTo(self.safeAreaLayoutGuide.snp.bottom).offset(-topBottomMargin)
        }
        
        //back view
        backView.backgroundColor = .clear
        scrollView.addSubview(backView)
        backView.snp.makeConstraints { (make) in
            make.top.bottom.equalTo(scrollView)
            make.height.equalTo(scrollView)
            make.left.equalTo(self).offset(backViewMargin)
            make.right.equalTo(self).offset(-backViewMargin)
        }
        
        //Login imageView
        let loginImageViewWithAppName = UIImageView(image: R.image.login_app_with_appname_icon())
        loginImageViewWithAppName.contentMode = .scaleAspectFit
        backView.addSubview(loginImageViewWithAppName)
        loginImageViewWithAppName.snp.makeConstraints { (make) in
            make.top.left.equalToSuperview()
            make.height.width.greaterThanOrEqualTo(0)
        }
        //loginImageView
        let loginImageViewWidthFor320: CGFloat = APPConfig.WidthForPortrait / 320 * 150//320是最小屏幕的宽度，按照这个比例设置图片
//        let loginImageViewHeightWidthRatio: CGFloat = 275 / 310 // 310, 275是图片的原始size
        let loginImageView = UIImageView(image: R.image.login_top_icon())
        //抗压缩的优先级最低
        loginImageView.setContentCompressionResistancePriority(UILayoutPriority.defaultLow, for: NSLayoutConstraint.Axis.vertical)
        loginImageView.contentMode = .scaleAspectFit
        backView.addSubview(loginImageView)
        loginImageView.snp.makeConstraints { (make) in
            make.top.equalTo(loginImageViewWithAppName.snp.bottom).offset(10)
            if APPConfig.WidthForPortrait == 320 {//值针对屏幕宽是320的
                make.centerX.equalToSuperview()
                make.width.equalTo(loginImageViewWidthFor320)
            }else{
                make.left.right.equalToSuperview()
            }
            make.height.greaterThanOrEqualTo(0)
        }
        //email title
        let emailTitleLabel = ContentLabel(R.font.interRegular(size: 15))
        emailTitleLabel.text = "Email"
        backView.addSubview(emailTitleLabel)
        emailTitleLabel.snp.makeConstraints { (make) in
            make.top.equalTo(loginImageView.snp.bottom).offset(20)
            make.left.equalToSuperview()
            make.height.width.greaterThanOrEqualTo(0)
        }
        //email input
        emailTextField.placeholder = "Enter email"
        emailTextField.clearButtonMode = .always
        emailTextField.keyboardType = .emailAddress
        emailTextField.returnKeyType = .next
        emailTextField.layer.borderColor = UIColor.clear.cgColor
        emailTextField.layer.borderWidth = 0
        emailTextField.backgroundColor = UIColor(hexStr: "#F5F5F5")
        emailTextField.setFont(R.font.interMedium(size: 17))
        emailTextField.showRightImageView("login_email_icon")
        backView.addSubview(emailTextField)
        emailTextField.snp.makeConstraints { (make) in
            make.top.equalTo(emailTitleLabel.snp.bottom).offset(8)
            make.left.right.equalToSuperview()
            make.height.equalTo(48)
        }
        //pwd title label
        let pwdTitleLabel = ContentLabel(R.font.interRegular(size: 15))
        pwdTitleLabel.text = "Password"
        backView.addSubview(pwdTitleLabel)
        pwdTitleLabel.snp.makeConstraints { (make) in
            make.top.equalTo(emailTextField.snp.bottom).offset(20)
            make.left.equalToSuperview()
            make.height.width.greaterThanOrEqualTo(0)
        }
        //pwd input
        pwdTextField.placeholder = "Enter Password"
        pwdTextField.returnKeyType = .go
        pwdTextField.isSecureTextEntry = true
        pwdTextField.clearButtonMode = .always
        pwdTextField.layer.borderColor = UIColor.clear.cgColor
        pwdTextField.layer.borderWidth = 0
        pwdTextField.backgroundColor = UIColor(hexStr: "#F5F5F5")
        pwdTextField.setFont(R.font.interMedium(size: 17))
        pwdTextField.tag = 0
        pwdTextField.showRightImageView("login_pwd_eye_btn_invisible") {[weak self] in
            guard let strongSelf = self else {return}
            strongSelf.pwdEyeImageClick()
        }
        backView.addSubview(pwdTextField)
        pwdTextField.snp.makeConstraints { (make) in
            make.top.equalTo(pwdTitleLabel.snp.bottom).offset(12)
            make.left.right.equalToSuperview()
            make.height.equalTo(48)
        }
        //login private policy
        let privatePolicyLabel = HyperlinkLabel.banner(content: "By logging on your agree to our ", alignment: .left, customStyling: translatesAutoresizingMaskIntoConstraints) { (title ,url) in
//            if UIApplication.shared.canOpenURL(url){
//                UIApplication.shared.open(url, options: [:], completionHandler: nil)
//            }
            if let naviagtionVC =  self.firstNaviViewController(){
                let vc = AttachmentViewController()
                vc.attchmentType = .OtherLink
                vc.attachmentURL = url.absoluteString
                vc.attachmentTitle = title
                naviagtionVC.pushViewController(vc, animated: false)
            }
        }
        privatePolicyLabel.addBanner(linkContentStr: R.string.localizable.privacyPolicy(), linkStr: APPConfig.serverAddress + APIConfig.LoginprivacyPolicy, customStyling: true)
        privatePolicyLabel.addStr(content: " and ")
        privatePolicyLabel.addBanner(linkContentStr: R.string.localizable.termsAndConditions(), linkStr: APPConfig.serverAddress + APIConfig.LoginTermsConditions, customStyling: true)
        
//        let privatePolicyLabel = HyperlinkLabel.banner(content: "By logging on your agree to our %0$@", linkContentStr: R.string.localizable.privacyPolicy(),linkStr: APPConfig.serverAddress + APIConfig.LoginprivacyPolicy,withAlignment: .left, customStyling: true, tapHandler: { url in
//            if UIApplication.shared.canOpenURL(url){
//                UIApplication.shared.open(url, options: [:], completionHandler: nil)
//            }
//        })
        privatePolicyLabel.numberOfLines  = 0
        privatePolicyLabel.adjustsFontSizeToFitWidth = true
        backView.addSubview(privatePolicyLabel)
        privatePolicyLabel.snp.makeConstraints { (make) in
            if APPConfig.WidthForPortrait <= 375 {
                make.top.equalTo(pwdTextField.snp.bottom).offset(10)
            }else{
                make.top.equalTo(pwdTextField.snp.bottom).offset(20)
            }
            make.left.right.equalToSuperview()
            make.height.greaterThanOrEqualTo(0)
        }
        
        //login button
        backView.addSubview(loginBtn)
        loginBtn.snp.makeConstraints { (make) in
            if APPConfig.WidthForPortrait <= 375 {
                make.top.equalTo(privatePolicyLabel.snp.bottom).offset(10)
            }else{
                make.top.equalTo(privatePolicyLabel.snp.bottom).offset(30)
            }
            make.height.equalTo(OperationButton.height)
            make.left.right.equalToSuperview()
        }
        //register
        registerBtn.setFont(R.font.interMedium(size: 14))
        registerBtn.setTitle(R.string.localizable.register(), for: UIControl.State.normal)
        registerBtn.setTitleColor(UIColor(hexStr: "#292D32B2"), for: UIControl.State.normal)
        backView.addSubview(registerBtn)
        registerBtn.snp.makeConstraints { (make) in
            make.top.greaterThanOrEqualTo(loginBtn.snp.bottom).offset(5)
            make.left.equalToSuperview()
            make.height.equalTo(30)
            make.width.greaterThanOrEqualTo(0)
            make.bottom.equalToSuperview()
        }
        //forget your password
        forgotPwdBtn.setFont(R.font.interMedium(size: 14))
        forgotPwdBtn.setTitle(R.string.localizable.forgotYourPassword(), for: UIControl.State.normal)
        forgotPwdBtn.setTitleColor(UIColor(hexStr: "#292D32B2"), for: UIControl.State.normal)
        backView.addSubview(forgotPwdBtn)
        forgotPwdBtn.snp.makeConstraints { (make) in
            make.centerY.equalTo(registerBtn)
            make.height.equalTo(30)
            make.width.greaterThanOrEqualTo(0)
            make.right.equalToSuperview()
        }
        self.addMoreLoginOptionBtn()
    }
    func addMoreLoginOptionBtn(){
        //1.先删除
        self.removeMoreLoginOption()
        //2.再增加
        let loginMoreOptions: [LoginMethodOperation] = LoginMethodServcie().getOtherLoginMethod(.password)
        if loginMoreOptions.count > 0{
            if self.moreLoginOptions.superview == nil{//不存在就增加
                backView.addSubview(moreLoginOptions)
                moreLoginOptions.snp.makeConstraints { make in
                    make.top.equalTo(loginBtn.snp.bottom).offset(16)
                    make.height.equalTo(40)
                    make.width.greaterThanOrEqualTo(0)
                    make.centerX.equalToSuperview()
                }
                registerBtn.snp.remakeConstraints { (make) in
                    make.top.greaterThanOrEqualTo(moreLoginOptions.snp.bottom).offset(5)
                    make.left.equalToSuperview()
                    make.height.equalTo(30)
                    make.width.greaterThanOrEqualTo(0)
                    make.bottom.equalToSuperview()
                }
                //
                
                moreLoginOptions.addTarget(self, action: #selector(moreOptionsClick), for: UIControl.Event.touchUpInside)
            }
        }else{
            registerBtn.snp.remakeConstraints { (make) in
                make.top.greaterThanOrEqualTo(loginBtn.snp.bottom).offset(5)
                make.left.equalToSuperview()
                make.height.equalTo(30)
                make.width.greaterThanOrEqualTo(0)
                make.bottom.equalToSuperview()
            }
        }
    }
    func removeMoreLoginOption(){
        //1.先删除more option btns
        if self.moreLoginOptions.superview != nil{
            self.moreLoginOptions.removeFromSuperview()
        }
        //2.在删除menu view
        if self.loginOptionsMenuView.superview != nil{
            self.loginOptionsMenuView.removeFromSuperview()
        }
    }
    @objc
    func moreOptionsClick(){
        if self.loginOptionsMenuView.superview == nil{
            loginOptionsMenuView.initMenuUI()
            self.addSubview(loginOptionsMenuView)
            loginOptionsMenuView.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
        }
    }
    //MARK: - 明文显示密码切换
    private func pwdEyeImageClick(){
        if self.pwdTextField.tag == 0 {
            self.pwdTextField.tag = 1
            self.pwdTextField.rightImageView?.image = R.image.login_pwd_eye_btn_visible()
            pwdTextField.isSecureTextEntry = false
        }else{
            self.pwdTextField.tag = 0
            self.pwdTextField.rightImageView?.image = R.image.login_pwd_eye_btn_invisible()
            pwdTextField.isSecureTextEntry = true
        }
    }
    func getLoginParams() -> LoginInfoModel {
        if self.emailTextField.isFirstResponder {
            self.emailTextField.resignFirstResponder()
        }
        
        if self.pwdTextField.isFirstResponder {
            self.pwdTextField.resignFirstResponder()
        }
        let model = LoginInfoModel()
        model.email = (self.emailTextField.text ?? "").trimmingCharacters(in: .whitespaces).lowercased()
        model.password = self.pwdTextField.text ?? ""
        return model
    }
    
}

